package com.quyunshuo.module.home.view

import android.content.Context
import android.graphics.Color.BLACK
import android.graphics.Typeface
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.res.ResourcesCompat
import com.quyunshuo.module.home.R

/**
 * 自定义textview统一字体、字重。
 */
class MhtTextView : AppCompatTextView {
    constructor(context: Context) : super(context) {
        init(null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        // 获取自定义属性
        if (attrs != null) {
            val a = context.obtainStyledAttributes(attrs, R.styleable.MhtTextView)
            val weight = a.getInt(R.styleable.MhtTextView_mhtTextWeight, NORMAL)
            applyFontWeight(weight)
            a.recycle()
        }
    }

    private fun applyFontWeight(weight: Int) {
        // 应用字重
        when (weight) {
            MEDIUM -> setTypeface(ResourcesCompat.getFont(context, R.font.outfit_medium))
            BOLD -> setTypeface(ResourcesCompat.getFont(context, R.font.outfit_bold))
            BLACK -> setTypeface(ResourcesCompat.getFont(context, R.font.outfit_black))
            else -> setTypeface(ResourcesCompat.getFont(context, R.font.outfit_regular))
        }
    }

    companion object {
        private const val NORMAL = 0
        private const val MEDIUM = 1
        private const val BOLD = 2
        private const val BLACK = 3
    }
}